import React, { PureComponent } from 'react';
import { Table, Form } from 'antd';
import { connect } from 'dva';
import styles from './index.less';
import EditableCell, { EditableContext } from './EditableCell';
import { timeFormat } from '@/utils/common';

const pageBaseConifg = {
  showQuickJumper: true,
  showSizeChanger: true,
  showTotal: total => `共${total}条`,
};
const COLUMN_ORDER = {
  title: '序号',
  key: 'order',
  width: 60,
  render: (text, record, index) => index + 1,
};

@connect(state => state.base)
// @Form.create()
class TableList extends PureComponent {
  static defaultProps = {
    // 是否初始化数据
    initialData: true,
    // 是否展示序号
    showOrder: false,
    // 表格行 key 的取值，可以是字符串或一个函数
    rowKey: 'id',
    // post请求
    post: false,
    page: 0,
    size: 10,
    // 设置列的对齐方式
    align: 'center',
    onRef: () => {},
    tableProps: {},
    autoFetch: true, //是否默认进行第一次请求
  };

  state = {
    loading: false,
    // 表格数据
    dataSource: [],
    // 搜索条件
    params: {
      // 当前页
      page: this.props.page,
      // 每页条数
      size: this.props.size,
      // 有可能会有些数据需要外面传进来的
      ...this.props.params,
    },
    pagination: {
      current: this.props.page,
      size: this.props.size,
      total: 0,
      ...pageBaseConifg,
    },
    handleTableChange: pagination => {
      this.setState(
        prevState => ({
          params: {
            ...prevState.params,
            page: pagination.current - 1,
            size: pagination.size,
          },
          pagination,
        }),
        () => {
          if (this.props.onChange) {
            this.props.onChange(pagination);
          }
          this.fetch(this.state.params);
        },
      );
    },
  };

  componentDidMount() {
    this.props.onRef(this);
    const { autoFetch, initialData } = this.props;
    if (initialData && autoFetch) {
      this.fetch(this.state.params);
    }
  }

  dataRender = list => {
    list.forEach(item => {
      Object.keys(item).forEach(key => {
        let column = this.props.columns.find(col => col.dataIndex == key);
        // 1, 时间格式化
        if (column && column.format) {
          if (column.format == 'timestamp') {
            item[key] = new Date(item[key]).getTime();
          } else {
            item[key] = timeFormat(item[key], column.format);
          }
        }
        // 2, 建设型
        if (key == 'buildType') {
          item[key] = this.props.dict.buildType.find(
            type => type.value == item[key],
          );
          item[key] = item[key] ? item[key].label : '';
        }

        // 2, 建设型
        if (key == 'projectStatus') {
          item[key] = this.props.dict.projectStatus.find(
            type => type.value == item[key],
          );
          item[key] = item[key] ? item[key].label : '';
        }
      });
    });
    return this.props.dataRender ? this.props.dataRender(list) : list;
  };
  /**
   * 开始请求
   */
  handler = () => {
    const isPost = this.props.post;
    const type = isPost ? '$request/post' : '$request/get';
    const data = isPost ? 'data' : 'params';

    const param = JSON.parse(JSON.stringify(this.state.params));
    Object.keys(param).forEach(k => {
      if (!param[k] && param[k] !== 0) delete param[k];
    });
    param.page = param.page < 0 ? 0 : param.page;
    this.props
      .dispatch({
        type,
        payload: {
          url: this.props.source,
          [data]: param,
        },
      })
      .then(res => {
        if (Array.isArray(res)) {
          this.handlerArrary(res);
        } else if (
          Object.prototype.toString.call(res) === '[object Object]' &&
          typeof res.page === 'undefined'
        ) {
          this.handlerSpecial(res);
        } else {
          this.handlerObject(res);
        }

        this.setState({ loading: false });
      });
  };

  handlerArrary = list => {
    this.setState(prevState => ({
      dataSource: this.dataRender(list),
      pagination: {
        size: prevState.pagination.size,
        total: list.length,
        ...pageBaseConifg,
      },
      handleTableChange: undefined,
    }));
  };

  handlerObject = res => {
    let ret = res;
    // if (!ret) {
    //   ret = {
    //     dataList: [],
    //     page: 1,
    //     size: this.state.pagination.size,
    //     totalPage: 1,
    //   };
    // }
    const { page } = this.state.params;
    // 假设数据共有21条，分页展示为10条，总展示3页，最后1页删除一条数据刷新无数据则退回上一页重新拉取数据
    if (
      page !== 0 &&
      ret.dataList.length === 0 &&
      this.state.pagination.total > 0
    ) {
      this.fetch({ page: page - 1 });
      return;
    }
    this.setState({
      dataSource: this.dataRender(ret.dataList),
      pagination: {
        current: ret.page + 1,
        size: ret.size,
        total: ret.totalCount,
        ...pageBaseConifg,
      },
    });
  };
  handlerSpecial = res => {
    // 非分页数据对象处理，需调用 dataRender 组装 dataSource 数据
    this.setState(prevState => {
      const dataSource = this.props.dataRender(res);
      return {
        dataSource,
        pagination: {
          size: prevState.pagination.size,
          total: dataSource.length,
          ...pageBaseConifg,
        },
        handleTableChange: undefined,
      };
    });
  };

  /**
   * 准备开始请求
   * @param {*} params
   */
  fetch = params => {
    this.setState(
      prevState => ({
        loading: true,
        params: { ...prevState.params, ...params },
      }),
      () => {
        this.handler();
      },
    );
  };

  getColumns = () => {
    let { columns } = this.props;
    const { showOrder, align } = this.props;
    if (showOrder) columns = [COLUMN_ORDER, ...columns];
    return columns.map(col => {
      const ret = { ...col, align: col.align || align };
      if (!col.editable) return ret;
      return {
        ...ret,
        onCell: record => ({
          record,
          type: col.editable.type,
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
          options: col.editable.options,
          config: col.editable.config,
          cprops: col.editable.compProps,
        }),
      };
    });
  };

  getDataList = () => this.state.dataSource;

  isEditing = record => record[this.props.rowKey] === this.props.editingKey;

  render() {
    const { loading, dataSource, pagination, handleTableChange } = this.state;
    const {
      rowKey,
      tableProps,
      dataSource: dataSourceProps,
      form,
      style,
    } = this.props;
    const components = { body: { cell: EditableCell } };
    return (
      <EditableContext.Provider value={form}>
        <div className={styles.tableList} style={style}>
          <Table
            components={components}
            bordered
            rowKey={rowKey}
            tableLayout="fixed"
            pagination={pagination}
            loading={loading}
            dataSource={dataSourceProps || dataSource}
            columns={this.getColumns()}
            onChange={handleTableChange}
            {...tableProps}
          >
            {this.props.children}
          </Table>
        </div>
      </EditableContext.Provider>
    );
  }
}
export default TableList;
